#!/bin/bash

#gentoo上依赖:
	#app-misc/jq  生成和解析json

#set -x

source shared_scripts/rfmAiGetPromptAndMultiModalFiles.sh
source shared_scripts/rfmAiJsonMessagesArray.sh
source shared_scripts/rfmAiProcessMultimodalFiles.sh

# Make the API call using curl
# Append the correct endpoint path to the base URL

if [ -n "$rfm_AI_MODEL_prompt" ]; then
    # 使用纯文本消息（原有逻辑）
    MESSAGES_ARRAY+=$(echo -e $rfm_AI_MODEL_prompt | jq -sR '{"role": "user", "content": .}')
fi

# 处理消息构建
if [ -n "$MULTIMODAL_MESSAGES" ]; then
    # 使用多模态消息
    MESSAGES_ARRAY+=$(echo "$MULTIMODAL_MESSAGES" | jq '.')
fi

# Build the JSON payload using the messages array format
REQUEST_JSON=$(echo $MESSAGES_ARRAY | jq -s \
  --arg model "$rfm_AI_MODEL_NAME" \
  --argjson temp "$rfm_AI_MODEL_TEMPERATURE" \
  '{
    model: $model,
    messages:.,
    stream: false,
    temperature: $temp
  }')

echo $REQUEST_JSON > .rfmAI_latest_request.json

# The JSON payload includes the model name and the user's prompt
RESPONSE=$(echo $REQUEST_JSON | curl -sS --fail-with-body -X POST "$rfm_AI_MODEL_HOST_URL" \
  -H "Authorization: Bearer $rfm_AI_MODEL_API_KEY" \
  -H "Content-Type: application/json" \
  -d @- 2>&1) # Capture stderr as well

# Check if curl failed (using --fail-with-body helps capture HTTP errors)
CURL_EXIT_CODE=$?
if [ $CURL_EXIT_CODE -ne 0 ]; then
    echo "Raw REQUEST_JSON for debug : $REQUEST_JSON" >&2
    echo "Raw RESPONSE for debug : $RESPONSE" >&2
    exit 4
fi


# Parse the response using jq
# Extract the response content or the error message
# Handles standard OpenAI format and potential error structures
RESULT=$(echo "$RESPONSE" | jq -r $'
if .error then
  "Error: " + (.error.message // .error | tostring)
elif .choices and (.choices | length > 0) and .choices[0].message then
  "reasoning:\n" + .choices[0].message.reasoning + "\ncontent:\n" + .choices[0].message.content
elif .choices and (.choices | length > 0) and .choices[0].text then
  .choices[0].text
else
  .message // ("Error: Unexpected API response format: " + (tostring))
end')

RESPONSE_ID=$(echo $RESPONSE | jq '.id')

source shared_scripts/rfmAiDisplayResult.sh

pushd $(pwd) 1>/dev/null
source shared_scripts/rfmAiSaveHistory.sh

# 通常是回复后先看，然后决定保存在哪里，保存好后，再打开慢慢看，而且保存好后，才能作为对话历史选中参与下一轮对话。

read -p "是否再次打开回复? [y/N] " openAgain
openAgain=${openAgain:-N}
if [[ "$openAgain" =~ ^[Yy]$ ]]; then
	if which bat >/dev/null 2>&1; then
    		echo "$filename" | xargs bat -p --language=md
	fi
fi

popd 1>/dev/null
